package xcmg.device.service.company;

import com.github.pagehelper.PageInfo;
import yb.ecp.fast.infra.util.PageHelperPlus;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xcmg.device.dao.entity.company.CompanyDealerDO;
import xcmg.device.dao.entity.company.EmployeeSettingDO;
import xcmg.device.dao.mapper.CompanyDealerMapper;
import xcmg.device.dao.mapper.company.EmployeeMapper;
import xcmg.device.dao.mapper.company.EmployeeSettingMapper;
import xcmg.device.infra.BeanUtil;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.ExportUtil;
import xcmg.device.service.vo.agent.ServiceBasicDataAgentVO;
import xcmg.device.service.vo.company.CompanyDealerVO;
import xcmg.device.service.vo.company.EmployeeSettingResultVO;
import xcmg.device.service.vo.company.EmployeeSettingVO;
import xcmg.device.service.vo.company.EmployeeVO;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * EmployeeSetting 后台接口实现类
 */
@Service
public class EmployeeSettingService {


    private static final Logger logger = LoggerFactory.getLogger(EmployeeSettingService.class);

    @Autowired
    private HttpServletResponse response;


    @Autowired
    private EmployeeSettingMapper employeeSettingMapper;


    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private CompanyDealerMapper companyDealerMapper;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private EmployeeSettingExcelService employeeSettingExcelService;

    @Autowired
    private FastGenClient fastGenClient;


    /**
     * 保存数据
     *
     * @param employeeSettingVO
     * @param userId
     * @param userName
     * @param orgId
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode save(EmployeeSettingVO employeeSettingVO, String userId, String userName, String orgId) throws Exception {
        doSave(employeeSettingVO, userName, orgId);
        return ErrorCode.Success;
    }


    /**
     * 根据状态，等信息保存数据
     *
     * @param employeeSettingVO
     * @param userName
     * @param orgId
     */
    private void doSave(EmployeeSettingVO employeeSettingVO, String userName, String orgId) throws Exception {
        EmployeeSettingDO employeeSettingDO = BeanUtil.do2bo(employeeSettingVO, EmployeeSettingDO.class);
        EmployeeSettingVO q = new EmployeeSettingVO();
        q.setOrgId(employeeSettingVO.getOrgId());
        q.setFactoryOrgId(orgId);
        q.setJobId(employeeSettingDO.getJobId());
        List<EmployeeSettingDO> ll = employeeSettingMapper.queryList(q);
        if (CollectionUtils.isNotEmpty(ll)) {
            employeeSettingDO = ll.get(0);
        }
        boolean isSuccess = false;
        employeeSettingDO.setUpdateName(userName);
        employeeSettingDO.setUpdateDate(new Date());
        if (StringUtils.isBlank(employeeSettingDO.getId())) {
            employeeSettingDO.setCreateName(userName);
            employeeSettingDO.setCreateDate(new Date());
            employeeSettingDO.setId(genId());
            employeeSettingDO.setFactoryOrgId(orgId);
            logger.info("新增操作，employeeSettingDO:{}", employeeSettingDO);
            isSuccess = employeeSettingMapper.insert(employeeSettingDO) > 0;

        } else {
            employeeSettingDO.setNumberEmp(employeeSettingVO.getNumberEmp());
            logger.info("编辑操作，employeeSettingDO:{}", employeeSettingDO);
            isSuccess = employeeSettingMapper.updateByPrimaryKeySelective(employeeSettingDO) > 0;
        }
        if (!isSuccess) {
            throw new Exception("保存记录失败");
        }
    }

    /**
     * 生成id
     *
     * @return
     * @throws Exception
     */
    private String genId() throws Exception {
        ActionResult<String> genResult = fastGenClient.textGuid();
        if (genResult.getCode() != ErrorCode.Success.getCode()) {
            throw new Exception("生成ID异常");
        }
        return genResult.getValue();
    }


    /**
     * 查询列表
     */
    public EmployeeSettingResultVO list(SearchCommonVO<EmployeeSettingVO> condition, boolean withStatics) {
        EmployeeSettingResultVO r = new EmployeeSettingResultVO();
        EmployeeSettingVO inParam = condition.getFilters();
        Map<String, Object> param = new HashMap<>();
        param.put("jobIdList", inParam.getJobIdList());
        param.put("jobList", inParam.getJobList());
        param.put("id", inParam.getId());
        List<ServiceBasicDataAgentVO> jobs = employeeService.queryJobListByMap(param);
        r.setJobs(jobs);
        String orgId = condition.getFilters().getOrgId();
        if (CollectionUtils.isNotEmpty(jobs)) {
            //查询所有供应商信息
            PageCommonVO<CompanyDealerDO> companyDealerPage = queryCompanyDealerDOList(condition);
            if (null != companyDealerPage && CollectionUtils.isNotEmpty(companyDealerPage.getPageInfoList())) {
                //查询所有供应商岗位配置信息,key:供应商orgId+"_"+岗位id  ，value：配置人数
                Map<String, Integer> configMap = genConfigMap(orgId);
                PageInfo<List<EmployeeSettingVO>> employeeSettingVoPage = new PageInfo();
                BeanUtils.copyProperties(companyDealerPage.getPageInfo(), employeeSettingVoPage, "list");
                employeeSettingVoPage.setList(new ArrayList<List<EmployeeSettingVO>>());

                Map<String, Integer> realMap = genRealMap(orgId, withStatics);

                for (CompanyDealerDO m : companyDealerPage.getPageInfoList()) {
                    List<EmployeeSettingVO> mList = new ArrayList<>(jobs.size());
                    for (ServiceBasicDataAgentVO vo : jobs) {
                        EmployeeSettingVO settingVO = new EmployeeSettingVO();
                        settingVO.setOrgId(m.getPlatOrgId());
                        settingVO.setOrgName(m.getCompanyName());
                        settingVO.setFactoryOrgId(orgId);
                        settingVO.setJobId(vo.getId());
                        settingVO.setJob(vo.getName());
                        String key = settingVO.getOrgId() + "_" + settingVO.getJobId();
                        Integer numberEmp = configMap.get(key);
                        numberEmp = null == numberEmp ? 0 : numberEmp;
                        settingVO.setNumberEmp(numberEmp);
                        if (withStatics) {
                            Integer numberEmpReal = realMap.get(key);
                            if (null == numberEmpReal) {
                                numberEmpReal = 0;
                            }
//                            Integer numberEmpReal = employeeService.countByJob(settingVO.getOrgId(), settingVO.getJobId());
                            settingVO.setNumberEmpReal(numberEmpReal);
                            settingVO.setNumberEmpNeed(numberEmp - numberEmpReal);
                        }
                        mList.add(settingVO);
                    }
                    employeeSettingVoPage.getList().add(mList);
                }
                r.setEmployeeSettingVOs(employeeSettingVoPage);
            }
        }
        return r;
    }

    private Map<String, Integer> genRealMap(String orgId, boolean withStatics) {
        Map<String, Integer> result = new HashMap<>();
        if (withStatics) {
            List<EmployeeVO> ll = employeeMapper.queryCountList(orgId);
            for (EmployeeVO v : ll) {
                String key = v.getOrgId() + "_" + v.getJobId();
                result.put(key, v.getAmount());
            }
        }
        return result;
    }

    /**
     * 根据当前主机厂orgId查询所有供应商信息
     *
     * @param condition
     * @return
     */
    private PageCommonVO<CompanyDealerDO> queryCompanyDealerDOList(SearchCommonVO<EmployeeSettingVO> condition) {
        PageCommonVO<CompanyDealerDO> pageCommonVO = new PageCommonVO();
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        CompanyDealerVO companyDealerVO = new CompanyDealerVO();
        companyDealerVO.setOrgId(condition.getFilters().getOrgId());
        companyDealerVO.setIsPlatCompany(true);
        companyDealerVO.setCompanyNameLikeList(condition.getFilters().getCompanyNameLikeList());
        List<CompanyDealerDO> companyDealerDOList = companyDealerMapper.list(companyDealerVO);
        pageCommonVO.setPageInfo(new PageInfo(companyDealerDOList));
        pageCommonVO.setPageInfoList(companyDealerDOList);
        return pageCommonVO;
    }

    public List<CompanyDealerDO> queryAllCompanyDealerDOList(String orgId) {
        CompanyDealerVO companyDealerVO = new CompanyDealerVO();
        companyDealerVO.setOrgId(orgId);
        companyDealerVO.setIsPlatCompany(true);
        List<CompanyDealerDO> companyDealerDOList = companyDealerMapper.list(companyDealerVO);
        return companyDealerDOList;
    }

    public Map<String, CompanyDealerDO> queryAllCompanyDealerDOKeyByNameList(String orgId) {
        Map<String, CompanyDealerDO> map = new HashMap<>();
        List<CompanyDealerDO> companyDealerDOList = queryAllCompanyDealerDOList(orgId);
        if (CollectionUtils.isNotEmpty(companyDealerDOList)) {
            for (CompanyDealerDO ddo : companyDealerDOList) {
                map.put(ddo.getCompanyName(), ddo);
            }
        }
        return map;
    }

    private Map<String, Integer> genConfigMap(String factoryOrgId) {
        Map<String, Integer> configMap = new HashMap<>();
        EmployeeSettingVO vo = new EmployeeSettingVO();
        vo.setFactoryOrgId(factoryOrgId);
        List<EmployeeSettingDO> ll = employeeSettingMapper.queryList(vo);
        if (CollectionUtils.isNotEmpty(ll)) {
            for (EmployeeSettingDO m : ll) {
                configMap.put(m.getOrgId() + "_" + m.getJobId(), m.getNumberEmp());
            }
        }
        return configMap;
    }


    public void export(String orgId) throws Exception {
        SearchCommonVO<EmployeeSettingVO> condition = new SearchCommonVO();
        condition.setFilters(new EmployeeSettingVO());
        condition.getFilters().setOrgId(orgId);
        condition.setPageNum(1);
        condition.setPageSize(Integer.MAX_VALUE);
        EmployeeSettingResultVO vo = list(condition, true);


        String title = "人员配置标准";
        ArrayList<String> rowsNameList = new ArrayList<>();
        rowsNameList.add("序号");
        rowsNameList.add("代理商");
        for (ServiceBasicDataAgentVO jb : vo.getJobs()) {
            rowsNameList.add(jb.getName());
        }
        String[] rowsName = new String[rowsNameList.size()];
        rowsNameList.toArray(rowsName);
        List<Object[]> dataList = new ArrayList<>();
        int i = 1;
        for (List<EmployeeSettingVO> list : vo.getEmployeeSettingVOs().getList()) {
            i = getRowObjectList(rowsName, dataList, i, list);
        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response);

    }

    private int getRowObjectList(String[] rowsName, List<Object[]> dataList, int i, List<EmployeeSettingVO> list) {
        Object[] objs = new Object[rowsName.length];
        objs[0] = i;
        objs[1] = list.get(0).getOrgName();
        int j = 2;
        for (EmployeeSettingVO vvo : list) {
            objs[j] = vvo.getNumberEmp();
            j++;
        }
        dataList.add(objs);
        return ++i;
    }


    public void exportRpt(String orgId) throws Exception {
        SearchCommonVO<EmployeeSettingVO> condition = new SearchCommonVO();
        condition.setFilters(new EmployeeSettingVO());
        condition.getFilters().setOrgId(orgId);
        condition.setPageNum(1);
        condition.setPageSize(Integer.MAX_VALUE);
        EmployeeSettingResultVO vo = list(condition, true);
        employeeSettingExcelService.exportRpt(vo);
    }


    @Transactional
    public void batchSave(List<EmployeeSettingDO> excelDatas) throws Exception {
        for (EmployeeSettingDO newDo : excelDatas) {
            EmployeeSettingVO q = new EmployeeSettingVO();
            q.setOrgId(newDo.getOrgId());
            q.setFactoryOrgId(newDo.getFactoryOrgId());
            q.setJobId(newDo.getJobId());
            List<EmployeeSettingDO> ll = employeeSettingMapper.queryList(q);
            if (CollectionUtils.isNotEmpty(ll)) {
                EmployeeSettingDO oldModel = ll.get(0);
                newDo.setId(oldModel.getId());
                newDo.setCreateName(oldModel.getCreateName());
                newDo.setCreateDate(oldModel.getCreateDate());
            }
            boolean isSuccess = false;
            if (StringUtils.isBlank(newDo.getId())) {
                newDo.setId(genId());
                logger.info("新增操作，employeeSettingDO:{}", newDo);
                isSuccess = employeeSettingMapper.insert(newDo) > 0;
            } else {
                logger.info("编辑操作，employeeSettingDO:{}", newDo);
                isSuccess = employeeSettingMapper.updateByPrimaryKeySelective(newDo) > 0;
            }
            if (!isSuccess) {
                throw new Exception("保存" + newDo.getOrgName() + "记录失败");
            }
        }
    }


}
